package com.example.springboot.controller;

import com.example.springboot.entity.Abandon;
import com.example.springboot.entity.Application;
import com.example.springboot.mapper.AbandonMapper;
import com.example.springboot.mapper.ApprovalMapper;
import com.example.springboot.mapper.DeviceMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.AbandonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/abandons")
public class AbandonController {

    @Autowired
    private AbandonMapper abandonMapper;

    @Autowired
    private AbandonService abandonService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private ApprovalMapper approvalMapper;

    //用get请求查询数据库信息
    @GetMapping
    public List<Abandon> findAll(){
        return abandonMapper.findAll();//查询所有数据
    }

    //用post请求对数据库数据进行增加和修改
    @PostMapping
    public Integer save(@RequestBody Abandon abandon){
        abandon.setApplierId(userMapper.selectId(abandon.getApplierName()));
        abandon.setDeviceId(deviceMapper.selectByNumber(abandon.getDeviceNumber()));
        return abandonService.save(abandon);//往数据库插入或更新数据
    }

    //按照审批状态分页查询
    @GetMapping("/page")
    public Map<String,Object> findStatus(@RequestParam Integer pageNum,
                                         @RequestParam Integer pageSize,
                                         @RequestParam String isApprove){
        pageNum = (pageNum - 1) * pageSize;
        Integer total = abandonMapper.selectTotal(isApprove);
        List<Abandon> data = abandonMapper.selectPage(pageNum,pageSize,isApprove);
        for(Abandon abandon : data){
            abandon.setDeviceNumber(deviceMapper.selectById(abandon.getDeviceId()));
            abandon.setApplierName(userMapper.selectName(abandon.getApplierId()));
        }
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    //用post请求对数据库数据进行增加和修改
    @PostMapping("/{id}")
    public int updateApprove(@PathVariable Integer id){

        Integer approvalId = approvalMapper.findLatest();
        abandonMapper.updateApproval(id,approvalId);
        return abandonMapper.updateApprove(id);//往数据库插入或更新数据
    }

    @GetMapping("/{id}")
    public List<Abandon> selectById(@PathVariable Integer id){
        List<Abandon> abandons = abandonMapper.selectById(id);
        for(Abandon abandon : abandons){
            abandon.setDeviceNumber(deviceMapper.selectById(abandon.getDeviceId()));
        }
        return abandons;
    }

}
